import { t } from 'i18next'
import useInit from '@/hooks/useInit'
import useStorageEvent from '@/hooks/useStorageEvent'
import { StyledWrap, StyledFooter } from './style'
import WebRecommendBrowser from '@/components/WebRecommendBrowser'
import Header from '@/components/Header'
import Main from './blocks/main'
import RightAction from './blocks/rightAction'
import { useRequest } from 'ahooks'
import { fetchGetMeetingInfo, fetchJdb, fetchMixMode, fetchMonitor } from '@/api/manager/main'
import { getUrlParams } from '@/utils'
import { useMccStore } from './store'
import Alert from '@/components/Alert'
import { fetchGetPlatformServiceUrl, fetchSetCookie } from '@/api/global'
import { MessageRun, cometdInit } from './utils/cometd'
import { useEffect } from 'react'
import { useGlobalStore } from '@/store/global'
import { useAIStore } from './blocks/ai/store'
import { useParamsStore } from './blocks/main/store'
import {
	fetchGetMeetingInfoInit,
	fetchDcsInit,
	fetchInteractiveInit,
	fetchOftenInit,
	fetchLiveInit,
	fetchAllMtsInit,
} from './store.fetch'
import { mccCascadeVOs } from './blocks/main/table/all/translator'
import Helper from './blocks/helper'
import { useMonitorStore } from './blocks/monitor/store'
import Vmp from './blocks/vmp'
import MtVmp from './blocks/mtVmp'
import { VmpGlobalStyle } from './blocks/vmp/style'
import VmpPlanSelectModal from './blocks/vmp/vmpPlanSelectModal'
import { animated, useSpring } from '@react-spring/web'
import AutoVmpDialog from '@/components/AutoVmpDialog'
import { usePlayVideoStore } from './blocks/playVideo/store'
import Monitor from './blocks/monitor'
import UpdateVideoModalView from './blocks/mccMtVideo/compontents/updateVideoModal'
const meetingMoid = getUrlParams('meetingMoid') ?? ''
function App() {
	useInit()
	useStorageEvent()
	const user = useGlobalStore((state) => state.user)
	const userLoaded = useGlobalStore((state) => state.userLoaded)
	const serverInfo = useGlobalStore((state) => state.serverInfo)
	const SWITCH = useGlobalStore((state) => state.SWITCH)
	//cometd建链
	useRequest(() =>
		fetchSetCookie({ meeting_moid: meetingMoid, type: 2 }, () => {
			cometdInit(meetingMoid)
		})
	)
	//会议信息
	const { loading: meetingInfoLoading } = useRequest(() => fetchGetMeetingInfo(meetingMoid), {
		onSuccess: (res) => {
			if (res.success && res.data) {
				let d = res.data
				useMccStore.setState({
					mccInfo: {
						createBy: {
							moid: d.creator?.account || '',
							name: d.creator?.name || '',
						},
						quantumEncryption: d.quantum_encryption || 0,
						encryptionType: d.encrypted_type || 0,
						preoccupy_resource: d.preoccupy_resource || 0,
						meetingResourceVO: {
							id: 9,
							name: t('192方'),
							multi: 192,
						},
						subject: d.name,
						meetingCategory: d.conf_category || 0,
						meetingType: d.conf_type,
						isUpload: d.cascade_upload || 0,
						superMtNum: d.enable_audience || 0,
						meetingMoid: d.meeting_moid,
						securityLevel: d.security_level || 0,
						voiceInspireState: d.voice_activity_detection || 0,
						voiceInspireTime: d.vacinterval || 3,
						e164: d.conf_id,
						startTime: d.start_time,
						duration: d.duration || 0,
						mediaFormat: d.video_formats?.[0]?.format || 3,
						mediaH264: d.media_h264 || 0,
						meetingRate: d.video_formats?.[0]?.bitrate || 2048,
						meetingResolution: d.video_formats?.[0]?.resolution || 13,
						frame: d.video_formats?.[0]?.frame || 30,
						password: d.password || '',
						meetingClosed: d.closed_conf || 0,
						meetingSafe: d.safe_conf || 0,
						watermark: d.watermark || 0,
						enableRtc: d.enable_rtc || 0,
						allowAnonymousMt: d.anonymous_mt || 0,
						doubleFlowLimit: d.dual_mode || 0,
						smartCascadeMode: d.smart_cascade_mode || 0,
						force_brd: d.force_brd || 0,
						chairman_mt_vmp_state: d.chairman_mt_vmp_state || 0,
						vmp_state: d.vmp_state || 0,
						mute: d.mute || 0,
						silence: d.silence || 0,
						vmpState: d.vmp_state || 0,
						chairmanMtVmpState: d.chairman_mt_vmp_state || 0,
						force_mute: d.force_mute || 0,
					},
					curPage: 'mcc_main',
				})
				fetchGetMeetingInfoInit({
					mccCascadeVOs: d.cascades
						? d.cascades
						: ([
								{
									id: '',
									mt_key: '0.0.0.0_0',
									mts: [],
								},
						  ] as unknown as mccCascadeVOs),
					vipList: d.vip || [],
					speaker: d.speaker || null,
					chairman: d.chairman || null,
					chairman_selectview: d.chairman_selectview || 0,
				})
				//设置放像
				usePlayVideoStore.getState().fetchInfo(false)
				//开始cometd处理
				MessageRun.startHandleMsg = true
			} else {
				Alert(
					!res.success && res.error_code === 52130
						? t('会议已结束(52130)')
						: res.description || t('获取会议信息异常'),
					() => {
						fetchGetPlatformServiceUrl()
							.then((data) => {
								window.location.href = data + '/index.html'
							})
							.catch((err) => {
								window.location.href = '/meeting/index.html'
							})
					}
				)
			}
		},
	})
	useRequest(() => fetchMixMode(meetingMoid), {
		onSuccess: (res) => {
			useMccStore.setState({ mixMode: res })
		},
	})
	const { loading: monitorLoading } = useRequest(() => fetchMonitor(), {
		onSuccess: (monitor_api_address) => {
			useMonitorStore.setState({
				monitorApiAddress: monitor_api_address || '',
			})
		},
	})
	useRequest(() => fetchJdb(meetingMoid), {
		onSuccess: (res) => {
			useMccStore.setState({ enableJdb: res })
		},
	})
	useEffect(() => {
		//personalConfig不会在session缓存里，确保user已经接口返回
		if (user && userLoaded && !meetingInfoLoading) {
			if (user.is_meeting_admin || useMccStore.getState().mccInfo.createBy.moid === user.moid) {
				useMccStore.setState({ isMeetingAdminOrCreator: true })
			} else {
				useMccStore.setState({ isMeetingAdminOrCreator: false })
			}
			if (useMccStore.getState().mccInfo.superMtNum) {
				useParamsStore.getState().superMeetingTab()
				fetchInteractiveInit()
			} else {
				fetchOftenInit()
			}
			fetchDcsInit()
			fetchLiveInit()
			fetchAllMtsInit()
		}
	}, [user, userLoaded, meetingInfoLoading])
	useEffect(() => {
		if (serverInfo && !meetingInfoLoading) {
			if (serverInfo.enable_kis && user?.enable_kis) {
				useAIStore.getState().fetchInit()
			}
		}
	}, [serverInfo, meetingInfoLoading, user])
	useEffect(() => {
		//user有storage所以初始值不是null ，某些useEffect情况需要额外判断
		if (user && userLoaded && !meetingInfoLoading && !monitorLoading && SWITCH.monitor) {
			useMonitorStore.setState({
				hasMonitor: user.enable_venue_monitor || 0,
				exeVersion: user.monitor?.exe_version || '',
				linuxVersion: user.monitor?.linux_arm_ft64_version || '',
				ssoCookieKey: user.sso_token || '',
				localIP: user.client_ip || '',
			})
			useMonitorStore.getState().init()
		}
	}, [user, userLoaded, meetingInfoLoading, monitorLoading, SWITCH])
	const curPage = useMccStore((state) => state.curPage)
	const meetingType = useMccStore((state) => state.mccInfo.meetingType)
	const collapsed = useMccStore((state) => state.collapsed)
	const hasSfuStyle = curPage === 'mcc_main' && meetingType === 2 ? true : false
	const animation = useSpring({
		width:
			meetingType === 2
				? hasSfuStyle
					? '160px'
					: curPage === 'tvwall'
					? '160px'
					: collapsed
					? '300px'
					: '19px'
				: hasSfuStyle
				? '160px'
				: collapsed
				? '300px'
				: '19px',
	})
	const animation1 = useSpring({
		width:
			meetingType === 2
				? hasSfuStyle
					? 'calc(100% - 160px)'
					: curPage === 'tvwall'
					? 'calc(100% - 160px)'
					: collapsed
					? 'calc(100% - 300px)'
					: 'calc(100% - 19px)'
				: hasSfuStyle
				? 'calc(100% - 160px)'
				: collapsed
				? 'calc(100% - 300px)'
				: 'calc(100% - 19px)',
		onResolve: (i) => {
			useParamsStore.getState().refreshTableWidth()
		},
	})
	return (
		<>
			<WebRecommendBrowser />
			<Header />
			<StyledWrap>
				{!['vmp', 'mtvmp'].includes(curPage) && (
					<>
						<animated.div style={animation1} className={`main-body`}>
							<Main />
						</animated.div>
						<animated.div style={animation} className={`main-right`}>
							<RightAction></RightAction>
						</animated.div>
					</>
				)}
				<VmpGlobalStyle />
				{curPage === 'vmp' && <Vmp />}
				{curPage === 'mtvmp' && <MtVmp />}
				<VmpPlanSelectModal />
				<AutoVmpDialog />
				<UpdateVideoModalView />
			</StyledWrap>
			<StyledFooter className="footer">
				<Helper />
			</StyledFooter>
			<Monitor />
		</>
	)
}
export default App
